package com.black.knight.chess.calls;

import org.restlet.data.ChallengeScheme;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.MenuInflater;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.black.knight.chess.ProfileActivity;
import com.black.knight.chess.R;
import com.black.knight.chess.SignInActivity;
import com.black.knight.chess.common.ActivityEnum;
import com.black.knight.chess.common.User;
import com.black.knight.chess.common.UsersResource;
import com.black.knight.chess.model.SahModel;
import com.black.knight.chess.model.SettingsModel;
import com.black.knight.chess.utils.Utils;

public class LoginUserCall implements Runnable {

	private User user;
	
	private SignInActivity context;
	
	private User base = null;
	
	private Boolean autoSignIn;
	
	public LoginUserCall(User user, SignInActivity context) {
		this.context = context;
		this.user = user;
	}
	
	@Override
	public void run() {
		final ClientResource cr = new ClientResource(SettingsModel.SERVICE_URL + "/users");
		
		cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, user.getUsername(), user.getPassword());
		cr.setRequestEntityBuffering(true);
		
		UsersResource resource = cr.wrap(UsersResource.class);
		
		try {
			base = resource.login((user));
		} catch (final Exception e) {
			if(e instanceof ResourceException && ((ResourceException) e).getStatus().getCode() == 401) {
				base = new User(false, context.getResources().getString(R.string.incorrect_username_or_password)); 
			} else {
				base = new User(false, context.getResources().getString(R.string.unable_to_connect_to_server));
			}
		}
		
		context.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					final ProgressBar progressBar = (ProgressBar) context.findViewById(R.id.progressBar);
					progressBar.setVisibility(ProgressBar.INVISIBLE);
					
					if(base.getSuccess()) {
						SettingsModel.getInstance().setLoggedUser(base);
						
						SettingsModel.getInstance().setAutoLogIn(autoSignIn);
						
						if(autoSignIn) {
							SettingsModel.getInstance().setUsername(user.getUsername());
							SettingsModel.getInstance().setPassword(user.getPassword());
							SettingsModel.getInstance().setAutoLogInWithFacebook(false);
						}
						
			        	MenuInflater inflater = SahModel.context.getMenuInflater();
			        	
			        	SahModel.context.menu.clear();
			            
			        	if(SettingsModel.getInstance().getLoggedUser() != null) {
			            	inflater.inflate(R.menu.chess_menu_signout, SahModel.context.menu);
			            } else {
			            	inflater.inflate(R.menu.chess_menu, SahModel.context.menu);
			            }
						
				    	TextView myMsg = new TextView(context);
				    	myMsg.setText(context.getResources().getString(R.string.user_logged_in_successfully));
				    	myMsg.setTextSize(18);
				    	myMsg.setTextColor(context.getResources().getColor(R.color.white));
				    	myMsg.setPadding(10, 20, 10, 20);
				    	myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
				    	
				    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
				    	builder.setView(myMsg)
				    	       .setPositiveButton(context.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
				    	           public void onClick(DialogInterface dialog, int id) {				    	        	   
				    	        	   context.finish();
				    	        	   
				    	        	    Intent intent4 = new Intent();
				   	        			intent4.setClass(SahModel.context, ProfileActivity.class);
				   	        			SahModel.context.startActivity(intent4);
				    	           }
				    	       });
				    	builder.create().show(); 
				    	
			        	PublishActivityCall call = new PublishActivityCall(ActivityEnum.SIGN_IN, base.getUsername(), base.getName(), "");			    		
			    		SettingsModel.EXECUTOR_SERVICE.execute(call);
					} else {
						Utils.displayAlertMessage(context, base.getMessage());
					}
				} catch (Exception e) { }
			}
		});
	}

	public Boolean getAutoSignIn() {
		return autoSignIn;
	}

	public void setAutoSignIn(Boolean autoSignIn) {
		this.autoSignIn = autoSignIn;
	}
}
